<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <!--表单组件-->
      <el-dialog :close-on-click-modal="false" v-model="addDialog" :title="title">
        <el-form ref="form" :model="form" :rules="rules" label-width="150px">
          <el-form-item label="商户" prop="shopId">
            <el-select v-model="form.shopId" filterable clearable placeholder="请选择" size="small">
              <el-option
                v-for="item in shopInfoList"
                :key="item.shopId"
                :label="item.shopName"
                :value="item.shopId"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="抖音门店Id">
            <el-input v-model="form.poiId" />
          </el-form-item>
          <el-form-item label="抖音门店名称">
            <el-input v-model="form.poiName" />
          </el-form-item>

          <el-form-item label="省市区（县）">
            <div id="app">
              <el-cascader size="large" :options="pcaTextArr" v-model="selectedOptions" />
            </div>
          </el-form-item>
          <el-form-item label="详细地址">
            <el-input type="textarea" :rows="3" v-model="form.address" />
          </el-form-item>

          <el-form-item label="门店经度">
            <el-input v-model="form.longitude" />
          </el-form-item>
          <el-form-item label="门店纬度">
            <el-input v-model="form.latitude" />
          </el-form-item>

          <el-form-item label="验证类型">
            <el-select v-model="form.verifyType" placeholder="请选择" size="small">
              <el-option :key="0" label="一次性核销" :value="0" />
              <el-option :key="1" label="分批次核销" :value="1" />
            </el-select>
          </el-form-item>

          <el-form-item label="授权能力" prop="modelsSessionList">
            <el-checkbox
              :indeterminate="isIndeterminate"
              v-model="checkAll"
              @change="handleCheckAllChange"
              >全选</el-checkbox
            >
            <div style="margin: 15px 0"></div>

            <el-checkbox-group v-model="form.modelsSessionList">
              <el-checkbox v-for="item in permissionTypeList" :label="item.key" :key="item.key">{{
                item.name
              }}</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-form>
        <div class="dialog-footer">
          <el-button type="text" @click="addDialog = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确认</el-button>
        </div>
      </el-dialog>

      <div>
        <div>
          <el-form
            :model="queryParams"
            ref="queryForm"
            :inline="true"
            v-show="showSearch"
            label-width="68px"
          >
            <el-form-item label="店铺名称">
              <el-select
                v-model="queryParams.shopId"
                filterable
                clearable
                placeholder="请选择"
                style="width: 240px"
              >
                <el-option
                  v-for="item in shopInfoList"
                  :key="item.shopId"
                  :label="item.shopName"
                  :value="item.shopId"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="">
              <el-input v-model="queryParams.poiName" placeholder="请输入抖音门店名称" clearable />
            </el-form-item>
            <el-form-item label="">
              <el-input v-model="queryParams.poiId" placeholder="请输入抖音门店Id" clearable />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleQuery">搜索</el-button>
              <el-button @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
        <div>
          <el-button type="success" round @click="handleAdd">添加配置信息</el-button>
        </div>
      </div>

      <!--表格渲染-->
      <el-table
        ref="table"
        v-loading="loading"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        :data="tiktokData"
        row-key="id"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="商户名称" prop="shopName" />
        <el-table-column label="抖音门店Id" prop="accountId" />
        <el-table-column label="抖音POIId" prop="poiId" />
        <el-table-column label="抖音门店名称" prop="poiName" />
        <el-table-column label="授权状态">
          <template #default="scope">
            {{
              formatDictMap('AUTHORIZATION_STATUS').find(
                (item) => item.value == scope.row.authorizationStatus,
              ).label
            }}
          </template>
        </el-table-column>
        <el-table-column label="验证类型">
          <template #default="scope">
            {{
              formatDictMap('VERIFY_TYPE').find((item) => item.value == scope.row.verifyType).label
            }}
          </template>
        </el-table-column>
        <el-table-column label="匹配任务执行状态">
          <template #default="scope">
            {{
              formatDictMap('MATCH_STATUS').find((item) => item.value == scope.row.matchStatus)
                .label
            }}
          </template>
        </el-table-column>
        <el-table-column label="匹配任务执行结果">
          <template #default="scope">
            {{
              formatDictMap('MATCH_RESULT').find((item) => item.value == scope.row.matchResult)
                .label
            }}
          </template>
        </el-table-column>
        <el-table-column label="授权能力" prop="modelsSession" />
        <el-table-column label="操作" width="240px" fixed="right">
          <template #default="scope">
            <el-button type="text" @click="handleAuthorize(scope.row)">抖音门店授权</el-button>
            <el-button type="text" @click="handleUpdate(scope.row)">抖音POI设置</el-button>
            <el-button type="text" @click="handleUpdate(scope.row)">修改</el-button>
            <el-button type="text" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-show="total > 0"
        :total="total"
        v-model:current-page="page.pageNum"
        v-model:page-size="page.pageSize"
        @change="getList"
      />
    </div>
  </div>
</template>

<script>
  import {
    list,
    add,
    update,
    remove,
    details,
    getPermissionTypeList,
    getAuthorizeUrl,
  } from '@/api/tiktok/douyinshop.js';
  import { getShopAllList } from '@/api/shop/shop.js';
  //   import AddRessSelect from '@/components/AddressSelect/index.vue';
  import { pcaTextArr } from 'element-china-area-data';
  import { getDictOptions } from '@/utils/dict';
  import { ElMessage, ElMessageBox } from 'element-plus';

  export default {
    name: 'DeviceTypeList',
    dicts: ['VERIFY_TYPE', 'MATCH_STATUS', 'MATCH_RESULT', 'AUTHORIZATION_STATUS'],
    // components: { AddRessSelect },
    data() {
      return {
        loading: false,
        single: true,
        multiple: true,
        tableDataList: [],
        addDialog: false,
        title: '添加配置信息',
        form: {},
        total: 0,
        page: {
          pageNum: 1, // 当前页数
          pageSize: 10, // 每页显示多少条
        },
        queryParams: {},
        showSearch: true,
        rules: {
          shopId: [{ required: true, message: '请选择商户', trigger: 'blur' }],
          modelsSessionList: [{ required: true, message: '请选择授权能力', trigger: 'blur' }],
        },
        tiktokData: [],
        shopInfoList: [],
        isStatus: true,
        permissionTypeList: [],
        isIndeterminate: false,
        checkAll: false,
        pcaTextArr,
        selectedOptions: [],
      };
    },
    created() {
      this.getList();
      getShopAllList({}).then((res) => {
        this.shopInfoList = res;
      });
      getPermissionTypeList().then((res) => {
        this.permissionTypeList = res;
      });
    },
    methods: {
      // 格式化字典
      formatDictMap(dictEnum) {
        return getDictOptions(dictEnum);
      },
      //授权能力是否全选
      handleCheckAllChange(val) {
        this.form.modelsSessionList = val ? this.getPermissionTypeList() : [];
        this.isIndeterminate = false;
      },
      getPermissionTypeList() {
        let permissionKeyList = [];
        this.permissionTypeList.forEach((element) => {
          permissionKeyList.push(element.key);
        });
        return permissionKeyList;
      },
      /** 抖音门店授权 */
      handleAuthorize(row) {
        const id = row.id;
        getAuthorizeUrl(id).then((res) => {
          window.open(res, '_blank');
        });
      },
      onAddRessSelect(row) {
        this.form.province = row[0];
        this.form.city = row[1];
        this.form.area = row[2];
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.page.pageNum = 1;
        this.getList();
      },
      /**
       * 搜索重置
       */
      resetQuery() {
        this.queryParams = {};
      },
      // 提交表单
      submitForm() {
        if (this.selectedOptions) {
          this.form.province = this.selectedOptions[0];
          this.form.city = this.selectedOptions[1];
          this.form.area = this.selectedOptions[2];
        }
        this.$refs['form'].validate((valid) => {
          if (valid) {
            if (this.form.id) {
              update(this.form).then(() => {
                ElMessage({
                  message: '修改成功',
                  type: 'success',
                });
                this.addDialog = false;
                this.getList();
              });
            } else {
              // 保存商品分类
              add(this.form).then(() => {
                ElMessage({
                  message: '新增成功',
                  type: 'success',
                });
                this.addDialog = false;
                this.getList();
              });
            }
          }
        });
      },
      // 新增类型
      handleAdd() {
        this.reset();
        this.addDialog = true;
        this.title = '添加抖音配置信息';
      },
      // 表单重置
      reset() {
        this.form = {
          shopId: undefined,
          poiId: undefined,
          poiName: undefined,
          province: undefined,
          city: undefined,
          address: undefined,
          longitude: undefined,
          latitude: undefined,
          verifyType: 0,
          id: undefined,
          modelsSessionList: [],
        };
        this.status = true;
      },
      /** 查询分类列表 */
      getList() {
        this.loading = true;
        list(this.page, this.queryParams).then((res) => {
          this.tiktokData = res.records;
          this.total = res.total;
          this.loading = false;
        });
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const id = row.id;
        if (!id) {
          ElMessage({
            message: '请选择需要修改的信息！',
            type: 'waring',
          });
          return;
        }
        details(id).then((res) => {
          this.form = res;
          this.addDialog = true;
          this.title = '修改抖音配置信息';
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const id = row.id;
        ElMessageBox.confirm('是否确认删除该项数据？')
          .then(function () {
            return remove(id);
          })
          .then(() => {
            this.getList();
            ElMessage({
              message: '删除成功',
              type: 'success',
            });
          })
          .catch(() => {});
      },
    },
  };
</script>

<style scoped></style>
